package com.spring.test.controller;

import com.spring.test.dao.RespBean;
import com.spring.test.entity.User;
import com.spring.test.service.UserService;
import com.spring.test.utils.MD5Utils;
import com.spring.test.utils.ValidateCode;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;


@RestController("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "获取个人信息接口")
    @GetMapping("getUserInfo")
    @ResponseBody
    public RespBean getUserInfo(String username){
        List<Object> userInfo = userService.getUserInfo(username);
        return RespBean.success(userInfo).add("msg","查询成功");
    }

    @ApiOperation(value = "获取所有考生信息")
    @GetMapping("getUser")
    @ResponseBody
    public RespBean getInfo() {

        List<Object> userList = userService.getUserList();
        for (Object o : userList) {
            System.out.println("o = " + o);
        }
        return RespBean.success(userList);
    }

    @ApiOperation(value = "考生注册")
    @PutMapping("addUser")
    @ResponseBody
    public RespBean setUser(@RequestParam("name") String name, @RequestParam("username") String username,
                            @RequestParam("password") String password,@RequestParam("validateCode") String valicode,
                            HttpServletRequest request)  {

        //首先进行验证码验证
        HttpSession session = request.getSession();
        // 取出session中的验证码与用户输入的作比较
        String validateCode = (String) session.getAttribute("validateCode");
        if (validateCode == null || validateCode.equals("")){
            return RespBean.fail().add("msg","请输入验证码");
        }
        if (!validateCode.toLowerCase().equals(valicode.toLowerCase())){
            return RespBean.fail().add("msg","验证码输入错误!");
        }

        if (userService.checkUserName(username) > 0) {
            return RespBean.fail();
        }
        User user = new User();
        user.setFullName(name);
        user.setUserName(username);
        user.setUserPassword(MD5Utils.encryptPassword(password));

        int i = userService.setUser(user);
        if (i == 1) {
            return RespBean.success();
        }

        return RespBean.fail();
    }

    @ApiOperation(value = "考生登录")
    @GetMapping("login")
    @ResponseBody
    public RespBean Login(@RequestParam("username") String username,
                          @RequestParam("password") String password,@RequestParam("validateCode") String valicode,
                          HttpServletRequest request) {

        //首先进行验证码验证
        HttpSession session = request.getSession();
        // 取出session中的验证码与用户输入的作比较
        String validateCode = (String) session.getAttribute("validateCode");
        if (validateCode == null || validateCode.equals("")){
            return RespBean.fail().add("msg","请输入验证码");
        }
        if (!validateCode.toLowerCase().equals(valicode.toLowerCase())){
            return RespBean.fail().add("msg","验证码输入错误!");
        }

        //根据用户名查询该账户是否存在
        if (userService.checkUserName(username) ==0) {
            return RespBean.fail().add("msg", "您还未注册请先注册");
        }
        //加密传过来的密码与做比较
        String s = MD5Utils.encryptPassword(password);
        if (userService.checkUserNameAndPwd(username, s)) {
            return RespBean.success(username).add("msg", "登录成功");
        }
        return RespBean.fail().add("msg", "密码错误，请重新输入");
    }
    @ApiOperation(value = "获取验证码")
    @GetMapping("/validateCode")
    public void validateCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 禁止图像缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //需要排除的字符
        String exChars = "0oOiIl1";
        String verifyCode = ValidateCode.generateTextCode(ValidateCode.TYPE_ALL_MIXED, 4, exChars);
        //将生成的验证码放入 Session ,方便登录进行判断
        request.getSession().setAttribute("validateCode", verifyCode);
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        BufferedImage bim = ValidateCode.generateImageCode(verifyCode, 90, 30, 5, true, Color.WHITE, Color.BLUE, null);
        ImageIO.write(bim, "JPEG", response.getOutputStream());
    }

    @ApiOperation(value ="修改个人信息")
    @PostMapping("/updateUserInfo")
    public RespBean upDateUserInfo(@RequestBody User user){
        System.out.println("user = " + user);
        String pwd = user.getUserPassword();
        String user_password =MD5Utils.encryptPassword(pwd);
        user.setUserPassword(user_password);
        if(userService.updateUserInfo(user)==1){
            return RespBean.success().add("msg_update","修改成功");
        }else {
            return RespBean.fail().add("msg_update","修改失败");
        }
    }

}
